<?php if(!defined('PUBLIC_DIR')) die('No Acces!');

Cnamespace('System');
class SQLiteDB implements iBaseDB {

	private $_link;
	private $_theQuery;
	private $_result;

	public function __construct($connection, $new = false){
		$pathinfo = pathinfo($connection);
		if($new && is_file($connection))
			unlink($connection);
		if(is_dir($pathinfo['dirname']) === false)
			trigger_error('Katalog '.$pathinfo['dirname'].' nie istnieje!', E_USER_ERROR);
		if(is_file($connection) === false){
			if(is_writable($pathinfo['dirname']) === false)
				trigger_error('Zapis w katalogu '.$pathinfo['dirname'].' jest niemożliwy!', E_USER_ERROR);
			if(!$new) trigger_error('Plik '.$connection.' nie istnieje. Zostanie stworzona czysta baza.', E_USER_NOTICE);
		}else if(is_readable($connection) === false)
			trigger_error('Odczyt pliku '.$connection.' jest niemożliwy!', E_USER_ERROR);
		else if(is_writable($connection) === false)
			trigger_error('Zapis do pliku '.$connection.' jest niemożliwy!', E_USER_ERROR);
		$this->_link = sqlite_open($connection, 0666, $error);
		if($this->_link === false)
			trigger_error($error, E_USER_ERROR);
	}

	public function Query($query){
		$this->_theQuery = $query;
		return $this->_result = sqlite_query($this->_theQuery, $this->_link);
	}

	public function GetQuery(){
		return $this->_theQuery;
	}

	public function GetResult(){
		return $this->_result;
	}

	public function NumFields($result = null){
		if($result !== null)
			return sqlite_num_fields($result);
		else
			return sqlite_num_fields($this->_result);
	}

	public function NumRows($result = null){
		if($result !== null)
			return sqlite_num_rows($result);
		else
			return sqlite_num_rows($this->_result);
	}

	public function FetchRow($result = null){
		if($result !== null)
			return sqlite_fetch_array($result, SQLITE_ASSOC);
		else
			return sqlite_fetch_array($this->_result, SQLITE_ASSOC);
	}

	public function FetchArray($result = null){
		if($result !== null)
			return sqlite_fetch_all($result, SQLITE_ASSOC);
		else
			return sqlite_fetch_all($this->_result, SQLITE_ASSOC);
	}

	public function Close(){
		return sqlite_close($this->_link);
	}
}